package algorithm.dichotomy.leetcode;

/**
 * @author: 柒月
 * @date: 2025/5/1 下午1:40
 * @version: 1.0
 */
public class Problem33 {

    // https://leetcode.cn/problems/search-in-rotated-sorted-array/
    public int search(int[] nums, int target) {
        if (nums == null) {
            return -1;
        }
        int head = 0, tail = nums.length - 1, left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] <= nums[tail]) { // 判断mid是否在小区间

                // 如果在小区间数组的最后一个大于target并且数组mid位置的值小于target就表示target在[mid+1,tail]位置
                if (target <= nums[tail] && nums[mid] < target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            } else {
                if (target >= nums[head] && nums[mid] > target){
                    right = mid - 1;
                }else {
                    left = mid + 1;
                }
            }
        }
        return -1;
    }
}
